package server.services;

import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;

import org.apache.log4j.Logger;

import server.control.Control;
import server.db.EntriesInteraction;
import server.jsons.Entry;
import server.jsons.GsonFactory;
import server.jsons.User;

import com.google.gson.Gson;

@Path("/entries")
public class EntriesService {
	private static Logger logger = Logger.getLogger(EntriesService.class.getName());
	
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public String categories(@QueryParam("sessionId") String sessionId, @QueryParam("when") String when){
		
		Control c = Control.getInstance();
		User u = c.getUser(sessionId);
		Gson json = GsonFactory.getGson();
		
		if(u != null){
			logger.info("User " + u.getUserEmail() + " requests his Categories.");
			
			
			return json.toJson(EntriesInteraction.obtainNewEntrySet(u, when));
		}else{
			logger.warn("Security: Unknown Session ID requests Categories. SessionID: " + sessionId);
			return null;
		}
	}
	
	@POST
	public String saveEntry(@QueryParam("sessionId") String sessionId, String text){
		Control c = Control.getInstance();
		User u = c.getUser(sessionId);
		Gson json = GsonFactory.getGson();
		Entry e = json.fromJson(text, Entry.class);
		
		if( u != null ){
			logger.info("User " + u.getUserEmail() + " saves Entry.");
			return new String("{\"id\":\"" + EntriesInteraction.saveEntry(e) + "\"}");
		}else{
			logger.warn("Security: Unknown Session ID tries to save Entries. SessionID: " + sessionId);
			return null;
		}
	}

}
